package com.chen.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.entity.UserEntity;
import com.chen.mapper.UserMapper;
import com.chen.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.utils.JWTUtils;
import com.chen.utils.Result;
import com.chen.utils.VxUtils;
import com.chen.vo.LoginParams;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cws
 * @since 2024-04-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Resource
    UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //加密盐
    private static final String slat = "kojonhsda!@#";

    /**
     * 微信登录
     *
     * @param code
     * @return
     */
    @Override
    public Result vxLogin(String code) {
//        https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
//        通过前端传的code，发起微信服务请求
        String weiXinOpenid = VxUtils.getWeiXinOpenid(code);
//        查询数据库
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getWxOpenid, weiXinOpenid));
        //获取Openid查询数据库判断该用户是够存在如果存在返回对应token
        if (Objects.isNull(userEntity)) {
            return Result.fail(500, "该微信用于未授权");
        }
        String token = JWTUtils.createToken(userEntity.getPhone());
        String key = "user:loginToken:" + token;
        String tokenKey = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNullOrEmpty(tokenKey)) {
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(userEntity), 1, TimeUnit.DAYS);
        }
//        返回token
        return Result.success(token);
    }

    /**
     * web登录
     *
     * @param loginParams
     * @return
     */
    @Override
    public Result webLogin(LoginParams loginParams) {
        if (StringUtils.isNullOrEmpty(loginParams.getPhone()) && StringUtils.isNullOrEmpty(loginParams.getPwd())) {
            return Result.fail(500, "账号或者密码不能为空");
        }
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhone, loginParams.getPhone()));
        if (Objects.isNull(userEntity)) {
            return Result.fail(500, "用户不存在，请注册~");
        }
        String pwd = DigestUtils.md5Hex(loginParams.getPwd() + slat);
        if (!pwd.equals(userEntity.getPwd())) {
            return Result.fail(500, "密码错误~");
        }
        String token = JWTUtils.createToken(userEntity.getPhone());
        String key = "user:loginToken:" + token;
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(userEntity), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result getPhoneRegister(String code, String phoneCode) {
        if (StringUtils.isNullOrEmpty(code)) {
            return Result.fail(500, "code不能为空");
        }
//        获取openid
        String weiXinOpenid = VxUtils.getWeiXinOpenid(code);
//        获取微信绑定的手机号
        String phoneObj = VxUtils.getPhone(phoneCode);
        String phoneNo = JSONUtil.parseObj(phoneObj).getStr("phoneNumber");
        if (StringUtils.isNullOrEmpty(phoneCode)) {
            return Result.fail(500, "授权微信手机号错误~");
        }
//        查询该用户是否在web网页注册过，如果注册添加openid即可
        UserEntity user = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhone, phoneNo));
        if (!Objects.isNull(user)) {
            user.setWxOpenid(weiXinOpenid);
            userMapper.updateById(user);
        } else {
            UserEntity userEntity = new UserEntity();
            userEntity.setPhone(phoneNo);
            userEntity.setSex("1");
            userEntity.setWxOpenid(weiXinOpenid);
//        默认手机号为登录密码
            userEntity.setPwd(DigestUtils.md5Hex(phoneNo + slat));
            userEntity.setStatus(1);
            userEntity.setVxAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
//      添加到数据库
            userMapper.insert(userEntity);
        }
//        存入redis
        String token = JWTUtils.createToken(phoneNo);
        String key = "user:loginToken:" + token;
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(user), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * web注冊
     *
     * @param loginParams
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result webRegister(LoginParams loginParams) {
//      查重
        UserEntity one = this.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhone, loginParams.getPhone()));
        if (!Objects.isNull(one)) {
            return Result.fail(500, loginParams.getPhone() + "手机号已注册~");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setPhone(loginParams.getPhone());
        userEntity.setPwd(DigestUtils.md5Hex(loginParams.getPwd() + slat));
        userEntity.setStatus(1);
        userEntity.setVxAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
        userEntity.setSex("1");
        boolean flag = this.save(userEntity);
        return flag ? Result.success("注冊成功~") : Result.fail(500, "注冊失敗~");
    }
}
